const { USD_XAU } = require("../../data/gold_price/curl");
const { PriceDao } = require("../dao/price");
const { PRICE_INTERVAL, PriceStack, Price } = require("../globalContext");

/**
 * 
 * @param { WebSocket Object } ws 
 */
module.exports.PriceWS = ws => {
    // Use Proxy to Decoupling
    const UsdXauPrice = new Proxy(new USD_XAU(PRICE_INTERVAL), {
        set(target, propKey, value, receiver) {
            if (propKey === 'price') {
                // console.log('set price', target, propKey, value, receiver);
                // emit price-update event
                ws.send(value);
                PriceStack.push(new Price({ price: value, c_time: Date.now() }))
                // log price to DataBase;
                PriceDao.logPrice(value);
            }
            return Reflect.set(target, propKey, value, receiver);
        }
    });

    const actions = {
        'start': () => {
            UsdXauPrice.start();
        },
        'stop': () => {
            UsdXauPrice.stop();
        }
    }

    ws.on('message', data => {
        console.log('goldPrice ws action %s @ %s ', data, Date.now());
        // switch (data) {
        //     case 'start': UsdXauPrice.start(); break;
        //     case 'stop': UsdXauPrice.stop(); break;
        //     default: ''
        // }
        actions[data] && actions[data]();
    });
}